#include <iostream>
#include <cstring>
#include <unistd.h>
#include <pthread.h>
#include <stdlib.h>
using namespace std;

string ToHex(pthread_t tid)
{
    char id[64];
    snprintf(id, sizeof(id), "0x%x", tid);
    return id;
}

void* threadRoutine(void* args)
{
    string name = static_cast<const char*>(args);
    usleep(1000);
    int cnt = 5;
    while(cnt--)
    {
        cout << "new thread is running, thread name: " << name << ", my thread id: " 
        << ToHex(pthread_self()) << endl;
        sleep(1);
    }
    pthread_exit(nullptr); 
}

int main()
{
    pthread_t tid;
    pthread_create(&tid, nullptr, threadRoutine, (void*)"thread-1");
    cout << "I am main thread, my thread id :" << ToHex(pthread_self()) << endl;

    int n = pthread_join(tid, nullptr); //阻塞式等待, 等待成功返回0, 等待失败返回错误码
    cout << "main thread done, " << " n : " << n << endl;
    return 0;
}